import { Html5Qrcode } from "html5-qrcode";
import { onMounted, ref } from "vue";

let result = ref("");

let html5QrCode = null;
// onMounted(() => {
//   html5QrCode = new Html5Qrcode("reader");
// });

const getImg = (e) => {
  console.log("e.target.file", e.target.files[0]);
  if (e.target.files.length == 0) return;
  const imageFile = e.target.files[0];
  html5QrCode
    .scanFile(imageFile, true)
    .then((decodedText) => {
      result.value = decodedText;
    })
    .catch((err) => {
      result.value = "扫码失败:\n" + err;
    });
};
export const useCamera = () => {
  html5QrCode = new Html5Qrcode("reader");
  Html5Qrcode.getCameras()
    .then((devices) => {
      /**
       * devices would be an array of objects of type:
       * { id: "id", label: "label" }
       */
      if (devices && devices.length) {
        var cameraId = devices[0].id;
        console.log("获取摄像头成功");
        console.log(cameraId);
        startCapture(cameraId);
        // .. use this to start scanning.
      }
    })
    .catch((err) => {
      // handle err
      console.log("没有获取到摄像头设备...");
    });
};

const startCapture = (cameraId) => {
  html5QrCode
    .start(
      cameraId,
      {
        fps: 10, // Optional, frame per seconds for qr code scanning
        qrbox: { width: 280, height: 270 }, // Optional, if you want bounded box UI
      },
      (decodedText, decodedResult) => {
        // do something when code is read
        console.log("result", decodedText);
        result.value = decodedText;
      },
      (errorMessage) => {
        // parse error, ignore it.
        // console.log("errorMesage:", errorMessage);
      }
    )
    .catch((err) => {
      // Start failed, handle it.
    });
};

const closeCamera = () => {
  html5QrCode
    .stop()
    .then((ignore) => {
      // QR Code scanning is stopped.
    })
    .catch((err) => {
      // Stop failed, handle it.
    });
};
